<template>
  <div class="app-container">
    <!-- 查询 -->
    <div class="filter-container">
      <el-row :gutter="0">
        <el-col :xs="24" :sm="18">
          <el-button class="filter-item" @click="refresh()">刷新</el-button>
        </el-col>
        <el-col :xs="24" :sm="6">
          <el-button class="filter-item" @click="print()" icon="el-icon-circle-plus">打印</el-button>
          <el-button class="filter-item" @click="importExcel()" icon="el-icon-circle-plus">导入</el-button>
          <el-button class="filter-item" @click="save()">保存</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 列表 -->
    <table>
      <tr>
        <td>试场号</td>
        <td>试场地址</td>
        <td v-for="xueke in data.xueke">{{xueke.xueke_name}}</td>
      </tr>
      <tr v-for="(shichang,i) in data.shichang">
        <td>{{shichang.num}}</td>
        <td>{{shichang.address}}</td>
        <td v-for="xueke in data.xueke">
         <input type="text" v-model="jiankaoTable[shichang.id][xueke.xueke_id]" />
        </td>
      </tr>
    </table>
    <el-dialog :title="importDialogTitle" :visible.sync="importDialog" top="1vh" :before-close="importCancel">
      <el-form ref="ref" label-width="200px" class="dialog-body" :style="{height:height+30+'px'}">
        <el-form-item label="监考导入模板下载" prop="remark">
          <el-button @click="download">导入模板下载</el-button>
        </el-form-item>
        <el-form-item label="监考导入" prop="remark">
          <el-upload
                name="excel_file"
                :show-file-list="false"
                :before-upload="uploadBefore"
                :action="uploadAction"
                :headers="uploadHeaders"
                :data="uploadData"
                :on-success="uploadSuccess"
                :on-error="uploadError"
              >
                <el-button type="primary">导入</el-button>
              </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importCancel">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import screenHeight from '@/utils/screen-height'
  import { getUserId, getToken } from '@/utils/auth'
  import { getJiaokaoTable,save,download } from '@/api/kaoshi_jiankao'

  export default {
    name: 'Kaoshi_jiankao',
    props: ['kaoshi_id','kaoshi_name'],
    data() {
      return {
        height: 680,
        loading: false,
        data: [],
        jiankaoTable: [],
        model: {
          int: '',
          teacher_id: '',
          shichang_id: '',
          xueke_id: '',
          kaoshi_id: '',
        },
        importDialog: false,
        importDialogTitle: '',
        uploadAction: process.env.VUE_APP_BASE_API + '/chengji/KaoshiJiankao/import',
        uploadHeaders: { UserId: getUserId(), Token: getToken() },
        uploadData: { user_id: getUserId(),kaoshi_id:this.kaoshi_id }
      }
    },
    created() {
      this.height = screenHeight()
      this.list()
    },
    methods: {
      print(){
        var printBox = document.getElementById('printBox');
        //拿到打印的区域的html内容
        var newContent =printBox.innerHTML;
        //将旧的页面储存起来，当打印完成后返给给页面。
        var oldContent = document.body.innerHTML;
        //赋值给body
        document.body.innerHTML = newContent;
        //执行window.print打印功能
        window.print();
        // 重新加载页面，以刷新数据。以防打印完之后，页面不能操作的问题
        window.location.reload();
        document.body.innerHTML = oldContent;
        return false;
      },
      save(){
        let jiankaoData=[];
        this.data.shichang.forEach(shichang => {
          this.data.xueke.forEach(xueke => {
            var teacherName = this.jiankaoTable[shichang.id][xueke.xueke_id];
            var teacher = this.data.teacher.find(function(elem) {
              return elem.name == teacherName;
            });
            if(teacher != null){
                jiankaoData.push({kaoshi_id:this.kaoshi_id,shichang_id:shichang.id,xueke_id:xueke.xueke_id,teacher_id:teacher.id})
            }
          })
        });
        save({
          kaoshi_id:this.kaoshi_id,
          jiankaoData: jiankaoData
        }).then(res => {
          this.list();
          this.$message.success(res.msg)
        })
      },
      // 列表
      list() {
        this.loading = true
        getJiaokaoTable({
          kaoshi_id: this.kaoshi_id
        }).then(res => {
          this.data = res.data
          this.data.shichang.forEach(shichang => {
            this.jiankaoTable[shichang.id] = new Array();
            this.data.xueke.forEach(xueke => {
              var jiankao = this.data.jiankao.find(function(elem) {
                return elem.shichang_id == shichang.id && elem.xueke_id == xueke.xueke_id
              });
              if (jiankao != undefined) {
                var teacher = this.data.teacher.find(function(elem) {
                  return elem.id == jiankao.teacher_id;
                });
                this.jiankaoTable[shichang.id][xueke.xueke_id] = teacher.name
              } else
                this.jiankaoTable[shichang.id][xueke.xueke_id] = ''
            })
          });
        }).catch(() => {
          this.loading = false
        })
      },
      // 刷新
      refresh() {
        this.query = this.$options.data().query
        this.list()
      },
      importExcel() {
        this.importDialog = true
        this.importDialogTitle = '导入'
      },
      uploadBefore(file) {
        this.loading = true
      },
      uploadSuccess(res, file) {
        if (res.code === 200) {
          this.loading = false
          this.$message.success(res.msg)
          this.importDialog = false
          this.list()
        } else {
          this.loading = false
          this.$message.error(res.msg)
        }
      },
      uploadError(error) {
        this.loading = false
        console.log(error)
      },
      importCancel(){
        this.importDialog = false
      },
      download()
      {
        download().then(response => {
          this.downloadFile(response);
          this.$message.success(response.msg)
        }).catch(function (error) {
          console.log(error);
        });
      },
      // 下载文件
      downloadFile (data) {
        if (!data) {
          return
        }
        let blob = new Blob([data])
        let fileName = '授课表导入模板.xlsx'
        if ('download' in document.createElement('a')) { // 不是IE浏览器
          let url = window.URL.createObjectURL(blob)
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        } else { // IE 10+
          window.navigator.msSaveBlob(blob, fileName)
        }
      }
    }
  }
</script>

<style scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  table {
    border-collapse: collapse;
    margin: 0 auto;
    text-align: center;
  }

  table td,
  table th {
    border: 1px solid #cad9ea;
    color: #666;
    height: 30px;
  }

  table thead th {
    background-color: #CCE8EB;
    width: 100px;
  }

  table tr:nth-child(odd) {
    background: #fff;
  }

  table tr:nth-child(even) {
    background: #F5FAFA;
  }

  input {
    outline-style: none;
    border: 0px;
    width: 70px;
  }
  .printcontainer{float:left}
  .biaoqianbox { width:350px; height:280px;float:left}
</style>
